// pages/my/addFeedback/addFeedback.js
const app = getApp();
var dataCut = require("../../../utils/dataCut");
var util = require("../../../utils/util");
import Toast from "../../../miniprogram_npm/@vant/weapp/toast/toast";
const Uid = require("../../../utils/uuid");
Page({
  /**
   * 页面的初始数据
   */
  data: {
    token: "",
    colortype: false, //提交按钮是否能点击
    strlength: 0, //输入的长度
    haveDesc: false, //是否输入了意见描述
    selectMediaList: [],
    wholeLength: 0, //照片数量
    isFullSucreen: app.globalData.isFullSucreen ? true : false, //判断机型
    uploadPercent: "0",
    overLength: 0,
    showUploadPercent: false, //展示上传进度条
    loading: false, //按钮loading状态
    nullarr: [],
  },
  showchoose() {
    var that = this;
    let len = that.data.selectMediaList.length || 0;
    let number = 3;
    console.log(len);
    if (len < 3) {
      number -= Number(len);
      that.chooseMedia(number);
    } else {
      Toast.fail("最多选择三个");
    }
  },
  // 选择上传图片和视频
  chooseMedia(number) {
    console.log(Uid.uuid(), "唯一");
    var that = this;
    console.log(number, "可选数量");
    wx.chooseMedia({
      count: number,
      mediaType: ["image", "video"],
      sourceType: ["album", "camera"],
      maxDuration: 20,
      camera: "back",
      success(res) {
        if (res.type == "image") {
          that.setData({
            selectMediaList: that.data.selectMediaList.concat(res.tempFiles),
          });
          // 路径为tempFilePath
        } else {
          let arr = res.tempFiles;
          if (arr[0].duration > 30) {
            // console.log(arr[0].size / 1048576);
            Toast.fail("视频最长30秒");
          } else {
            arr[0].duration = that.formatSeconds(Math.ceil(arr[0].duration));
            arr[0].type = "video";
            that.setData({
              selectMediaList: that.data.selectMediaList.concat(arr),
            });
          }
        }
        // 视频缩略图thumbTempFilePath
        // 视频时长duration
        // 路径tempFilePath
        that.setData({
          wholeLength: that.data.selectMediaList.length,
        });
        // console.log(res);
      },
    });
  },
  previewMedia(e) {
    console.log(e.currentTarget.dataset.index);
    let that = this;
    let list = that.data.selectMediaList;
    let sources = [];
    for (let i = 0; i < list.length; i++) {
      if (list[i].type) {
        sources[i] = {
          url: list[i].tempFilePath,
          type: "video",
          poster: list[i].thumbTempFilePath,
        };
      } else {
        sources[i] = {
          url: that.data.selectMediaList[i].tempFilePath,
        };
      }
    }
    let index = e.currentTarget.dataset.index;
    let type = e.currentTarget.dataset.type;
    wx.previewMedia({
      sources: sources,
      current: index,
      success(res) {
        console.log("成功", res);
      },
    });
  },
  // 时间转化格式
  formatSeconds(value) {
    let result = parseInt(value);
    // let h = Math.floor(result / 3600) < 10 ? '0' + Math.floor(result / 3600) : Math.floor(result / 3600);
    let m =
      Math.floor((result / 60) % 60) < 10
        ? Math.floor((result / 60) % 60)
        : Math.floor((result / 60) % 60);
    let s =
      Math.floor(result % 60) < 10
        ? "0" + Math.floor(result % 60)
        : Math.floor(result % 60);

    let res = "";
    // if(h !== '00') res += `${h}h`;
    if (m !== "00") res += `${m}:`;
    res += `${s}`;
    return res;
  },
  delMedia(e) {
    let arr = this.data.selectMediaList;
    arr.splice(e.currentTarget.dataset.index, 1);
    console.log(arr, "1111");
    this.setData({
      selectMediaList: arr,
      wholeLength: arr.length,
    });
  },

  textareaChange(e) {
    if (e.detail.value == "") {
      this.setData({
        strlength: 0,
        haveDesc: false,
      });
      this.showButton();
    } else {
      this.setData({
        strlength: dataCut.strLength(e.detail.value),
        haveDesc: true,
      });
      this.showButton();
    }
  },
  showButton() {
    if (this.data.haveDesc) {
      this.setData({
        colortype: true,
      });
    } else {
      this.setData({
        colortype: false,
      });
    }
  },
  SubmitForm(e) {
    let that = this;
    // console.log(e.detail.value);
    if (that.data.colortype) {
      let mediaList = that.data.selectMediaList;
      let countNumber = that.data.selectMediaList.lenth;
      // 如果上传照片和视频
      if (that.data.wholeLength !== 0) {
        that.setData({
          showUploadPercent: true,
        });
        for (let i = 0; i < mediaList.length; i++) {
          let url = mediaList[i].tempFilePath;
          let type = url.substr(url.length - 4);
          let saveKey = Uid.uuid() + type;
          if (mediaList[i].type) {
            let signatureType = "video";
            that.getSignature(saveKey, signatureType, function (res) {
              // console.log("上传秘钥", res.data.data);
              mediaList[i].bucket = res.data.data.bucket;
              mediaList[i].domain = res.data.data.domain;
              mediaList[i].policy = res.data.data.policy;
              mediaList[i].operator = res.data.data.operator;
              mediaList[i].signature = res.data.data.signature;
              that.setData({
                selectMediaList: mediaList,
              });
              that.Upload("video", i, function (res) {
                let arr = that.data.selectMediaList;
                arr[i].imgUrl =
                  that.data.selectMediaList[i].domain + "/" + res.url;
                // console.log(that.data.overLength + 1);
                that.setData({
                  selectMediaList: arr,
                  overLength: that.data.overLength + 1,
                  uploadPercent: Math.ceil(
                    ((that.data.overLength + 1) / that.data.wholeLength) * 100
                  ),
                });
                // console.log("i", i);
              });
            });
          } else {
            let signatureType = "img";
            that.getSignature(saveKey, signatureType, function (res) {
              // console.log("上传秘钥", res.data.data);
              mediaList[i].bucket = res.data.data.bucket;
              mediaList[i].domain = res.data.data.domain;
              mediaList[i].policy = res.data.data.policy;
              mediaList[i].operator = res.data.data.operator;
              mediaList[i].signature = res.data.data.signature;
              that.setData({
                selectMediaList: mediaList,
              });

              that.Upload("image", i, function (res) {
                let arr = that.data.selectMediaList;
                arr[i].imgUrl =
                  that.data.selectMediaList[i].domain + "/" + res.url;
                // console.log(that.data.overLength + 1);
                that.setData({
                  selectMediaList: arr,
                  overLength: that.data.overLength + 1,
                  uploadPercent: Math.ceil(
                    ((that.data.overLength + 1) / that.data.wholeLength) * 100
                  ),
                });
                console.log("i", i);
              });
            });
          }
        }
        const time = setInterval(() => {
          if (that.data.uploadPercent == 100) {
            console.log("完成");
            clearInterval(time);
            that.addRequest(e.detail.value);
          } else {
            console.log("1");
          }
        }, 100);
      } else {
        // console.log(countNumber);
        console.log(e.detail.value);

        that.addRequest(e.detail.value);
        // setTimeout(function () {
        //   that.setData({
        //     showUploadPercent: false,
        //   });
        // }, 500);
      }
    } else {
    }
  },
  addRequest(options) {
    let that = this;
    let arr1 = that.data.selectMediaList;
    let imglistString = "";
    let videolistString = "";
    for (let j = 0; j < arr1.length; j++) {
      if (arr1[j].type) {
        videolistString += "," + arr1[j].imgUrl;
      } else {
        imglistString += "," + arr1[j].imgUrl;
      }
    }

    imglistString = imglistString.slice(1, imglistString.length);
    videolistString = videolistString.slice(1, videolistString.length);

    var params = {
      feedBackId: that.data.feedBackId,
      comment: options.textarea,
      image: imglistString,
      video: videolistString,
    };
    console.log("进行到提交", params);
    util.postToken("/wechat/feedback/reply", params, that.data.token, function (
      res
    ) {
      if (res.status_code == 200) {
        Toast.success("感谢您的反馈");
        that.setData({
          colortype: false, //提交按钮是否能点击
          strlength: 0, //输入的长度
          haveDesc: false, //是否输入了意见描述
          selectMediaList: [],
          wholeLength: 0, //照片数量
          uploadPercent: "0",
          overLength: 0,
          showUploadPercent: false, //展示上传进度条
          loading: false, //按钮loading状态
          nullarr: [],
        });
        setTimeout(function () {
          that.onLoad();
          wx.navigateBack();
        }, 1500);
      } else {
      }
      console.log("提交反馈", res);
    });
  },
  // 获取上传资源秘钥
  getSignature(saveKey, signatureType, callback) {
    wx.request({
      url: "http://api.lianc.vip/oss/getSignature",
      method: "GET",
      header: {
        "content-type": "application/x-www-form-urlencoded",
        Authorization: "Bearer " + app.globalData.token,
      },
      data: {
        saveKey: "/feedback/image/" + saveKey,
        signatureType: signatureType,
      },
      success: function (res) {
        callback(res);
      },
    });
  },
  // 上传图片或视频
  Upload(type, i, callback) {
    let that = this;
    let datalist = that.data.selectMediaList;
    const UploadTask = wx.uploadFile({
      url: "https://v0.api.upyun.com/" + datalist[i].bucket,
      filePath: datalist[i].tempFilePath,
      name: "file",
      formData: {
        authorization:
          "UPYUN " + datalist[i].operator + ":" + datalist[i].signature,
        policy: datalist[i].policy,
      },
      success: function (res) {
        // console.log("上传", JSON.parse(res.data));
        callback(JSON.parse(res.data), UploadTask);
      },
    });
    UploadTask.onProgressUpdate(function (res) {
      // console.log("进度", res.progress);
      // console.log("已上传长度", res.totalBytesSent);
      // console.log("预期上传", res.totalBytesExpectedToSend);
    });
  },

  onClickHide() {
    // this.setData({
    //   showUplo adPercent: false,
    // });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var token = wx.getStorageSync("token");
    let that = this;
    this.setData({
      token,
      feedBackId:options.id
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {},
});
